﻿using System;
using System.Diagnostics;
using System.IO;
using FluentNHibernate.Cfg;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;

namespace SevenDigital.EndUserManagement.Core.Mapping
{
	public class NHibernateConfiguration
	{
		public FluentConfiguration BuildFluentConfigurationForLocalDB() {
			return BuildFluentConfiguration("local.hibernate.cfg.xml");
		}

		public ISessionFactory BuildSessionFactoryForLocalDB() {
			var cfg = BuildFluentConfigurationForLocalDB()
				.BuildConfiguration();

			new SchemaExport(cfg)
			.SetOutputFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
										"buildScript.sql"))
			.Create(false, true);

			try {
				return cfg.BuildSessionFactory();
			}
			catch(Exception ex) {
				Debug.WriteLine(ex);
				throw ex;
			}
		}
		public ISessionFactory BuildSessionFactory() {
			return BuildSessionFactory(String.Empty);
		}


		public ISessionFactory BuildSessionFactory(string configurationFileName) {
			var cfg = BuildFluentConfiguration(configurationFileName);

			return cfg.BuildSessionFactory();
		}

		private FluentConfiguration BuildFluentConfiguration(string configurationFileName) {
			var cfg = new Configuration();
			if (String.IsNullOrEmpty(configurationFileName)) {
				cfg.Configure();
			} else {
				cfg.Configure(Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
				                           configurationFileName));
			}

			return Fluently
				.Configure(cfg)
				.Mappings(m =>{
				          	m.FluentMappings.AddFromAssemblyOf<UserMap>()
				          		.ExportTo(AppDomain.CurrentDomain.BaseDirectory);
				          	m.HbmMappings.AddFromAssemblyOf<UserMap>();
				          });
		}
	}
}